/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package eproject.utilitity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author khiemtd
 */
public class Validation {

    public static boolean checkValidNumericIdString(String value) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            return value.matches("^[0-9]+$");
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkEqualsExternalValue(String value,
            String externalValue) {
        if (value == null || value.isEmpty() || value.trim().isEmpty()) {
            return true;
        }

        boolean isValid = ((value.equals(externalValue)) ? true : false);

        return isValid;
    }

    public static boolean checkExistsInStringGroup(String value, String[] group) {
        if (value.trim().isEmpty()) {
            return true;
        }
        boolean isValid = false;
        for (int i = 0; i < group.length; i++) {
            if (group[i].equals(value)) {
                isValid = true;
                break;
            }
        }
        return isValid;
    }

    public static boolean checkMatchCustomRegex(String value, String patternString) {
        if (value.trim().isEmpty() == false) {
            Pattern pattern = Pattern.compile(patternString);
            Matcher matcher = pattern.matcher(value);
            return matcher.matches();
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkMaxLengthConstraint(String value, int maxLength) {
        if (value.trim().isEmpty() == false) {
            return ((value.trim().length() > maxLength) ? false : true);
        } else {
            return true;//null value - no need to check
        }

    }

    public static boolean checkMinLengthConstraint(String value, int minLength) {
        if (value.trim().isEmpty() == false) {
            return ((value.trim().length() < minLength) ? false : true);
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkValidFormatName(String value) {
        if (value.trim().isEmpty() == false) {
            Pattern pattern = Pattern.compile("[$0-9+,:;=@#|{}\\`_%!/]");
            Matcher matcher = pattern.matcher(value);
            return !matcher.find();
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkValidEmail(String value) {

        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            boolean isValid = true;
            String email_pt = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
            Pattern pattern = Pattern.compile(email_pt);
            Matcher matcher = pattern.matcher(value);
            isValid = matcher.matches();
            if (isValid) {
                //count number of @
                int firstOcc = value.indexOf("@");

                int lastOcc = value.lastIndexOf("@");

                if (firstOcc != lastOcc) {
                    isValid = false;
                }
            }
            return isValid;
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkValidIdString(String value) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            return value.matches("^[A-Za-z_0-9\\-]+$");
        } else {
            return true;//null value - no need to check
        }
    }

    @SuppressWarnings("unused")
    public static boolean checkValidIntegerString(String value) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            try {
                Integer integerValue = Integer.parseInt(value);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        } else {
            return true;//null value - no need to check
        }
    }

    @SuppressWarnings("unused")
    public static boolean checkValidNumericString(String value) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            try {
                Float floatValue = Float.parseFloat(value);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkValidPositiveAmount(String value) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            try {
                Float floatValue = Float.parseFloat(value);
                return (floatValue >= 0);
            } catch (NumberFormatException e) {
                return false;
            }
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkValidDate(String value, String checkPattern) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {

            Date testDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat(checkPattern);
            sdf.setLenient(false);
            try {
                testDate = sdf.parse(value);
			// if the format of the string provided doesn't match the format we
                // declared in SimpleDateFormat() we will get an exception
            } catch (ParseException e) {
                return false;
            }
			 // dateformat.parse will accept any date as long as it's in the format
            // you defined, it simply rolls dates over, for example, december 32
            // becomes jan 1 and december 0 becomes november 30
            // This statement will make sure that once the string
            // has been checked for proper formatting that the date is still the
            // date that was entered, if it's not, we assume that the date is invalid
            if (!sdf.format(testDate).equals(value)) {
                return false;
            } else {
                //get upper limit date
                Calendar cal = Calendar.getInstance();
                cal.set(Calendar.YEAR, 10000);
                cal.set(Calendar.MONTH, Calendar.JANUARY);
                cal.set(Calendar.DATE, 1);
                Date upperLimitDate = cal.getTime();
                if (testDate.after(upperLimitDate)) {
                    return false;
                } else {
                    return true;
                }
            }
        } else {
            return true;//null value - no need to check
        }
    }

    public static boolean checkSpecialCharacter(String value, boolean includeSpace) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            Pattern pattern = Pattern.compile("[$&+,:;=?@#|]");
            if (includeSpace == true) {
                pattern = Pattern.compile("[$&+,:;=?@#| ]");
            }
            Matcher matcher = pattern.matcher(value);
            if (matcher.find() == true) {
                return false;
            }
            return true;
        } else {
            return true;
        }
    }

    public static boolean checkValidUnicodeAlphanumericString(String value) {
        boolean isValid = true;
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            int sz = value.length();
            for (int i = 0; i < sz; i++) {
                if ((Character.isLetterOrDigit(value.charAt(i)) == false)
                        && (value.charAt(i) != ' ')
                        && (value.charAt(i) != '_')
                        && (value.charAt(i) != '-')
                        && (value.charAt(i) != '\\')
                        && (value.charAt(i) != '/')) {
                    isValid = false;
                    break;

                }
            }
        }
        return isValid;
    }

    public static boolean checkValidPhone(String value) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            return value.matches("^(?:\\+84(?:-)?|0\\d{2,4}-|0|)\\d{7,25}$");
            /*
             Pattern pattern = Pattern
             .compile("^(?:\\+84(?:-)?|0\\d{2,4}-|0|)\\d{7,10}+$");
             Matcher matcher = pattern.matcher(value);
             return matcher.matches();
             */
        } else {
            return true;
        }

    }

    /**
     * @author khiemtd
     */
    public static boolean checkRequiredString(String value) {
        return (value == null || value.isEmpty() || value.trim().isEmpty()) ? false : true;
    }

    /**
     * @author khiemtd
     */
    public static boolean checkOverloadSizeString(String value, int limitSize) {
        if (value != null) {
            if (value.trim().length() > limitSize) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static boolean checkMatchRegularExp(String valueToMatch, String regularExp) {
        if (valueToMatch == null) {
            return true;
        } else {
            Pattern pattern = Pattern.compile(regularExp);
            Matcher matcher = pattern.matcher(valueToMatch);
            return matcher.matches();
        }
    }

    /**
     * @author thachtv
     * @param input
     * @param pattern("^[a-zA-Z0-9_\\-@#$.]*$")
     * @return boolean
     */
    public static final boolean checkRegex(String input, String pattern) {
        Pattern p = Pattern.compile(pattern);
        if (p.matcher(input).matches()) {
            return true;
        }
        return false;
    }

    /**
     * @author thachtv
     * @param str
     * @return boolean
     */
    public static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\d+)?");  //match a number with optional '-' and decimal.
    }

    /**
     * @author thachtv
     * @param value
     * @return boolean
     */
    public static boolean checkSpecialCharacterXSS(String value, String pattern) {
        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
            Pattern pat = Pattern.compile(pattern);
            Matcher matcher = pat.matcher(value);
            return matcher.find();
        } else {
            return true;
        }
    }
}
